package com.rongzhe.house.ui.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.rongzhe.house.R;
import com.rongzhe.house.manager.ConfigManager;
import com.rongzhe.house.presenter.BasePresenter;
import com.rongzhe.house.utils.UIUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by huang on 2017/12/10.
 */

public class HouseEntrustmentFragment2 extends BaseFragment {

    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.webview)
    BridgeWebView webview;
    Unbinder unbinder;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.activity_h5_base, container, false);
        unbinder = ButterKnife.bind(this, root);
        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initWebView();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onResume() {
        super.onResume();
        webview.onResume();
        //对网页显示设置字体缩放, 禁止字体大小改变, 防止页面布局错乱
        Resources resource = getResources();
        Configuration configuration = resource.getConfiguration();
        configuration.fontScale = 1.0f;//设置字体的缩放比例
        resource.updateConfiguration(configuration, resource.getDisplayMetrics());
    }

    @Override
    public void onStart() {
        super.onStart();
        loadUrl(ConfigManager.getInstance().getEntrustPage());
    }

    @Override
    public void onPause() {
        super.onPause();
        webview.onPause();
    }

    public boolean handleBackPressed() {
        if (webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return false;
    }

    private void loadUrl(String url) {
        webview.loadUrl(url);
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) { // 进度
            super.onProgressChanged(view, newProgress);

            if (newProgress == 100) {
                progress.setVisibility(View.GONE);// 加载完网页进度条消失
            } else {
                progress.setVisibility(View.VISIBLE);// 开始加载网页时显示进度条
                progress.setProgress(newProgress);// 设置进度值
            }
        }
    }

    //初始化webview
    private void initWebView() {
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true); // 启用支持javascript
        webSettings.setAllowFileAccess(true);// 可以访问文件

        webSettings.setBuiltInZoomControls(true);// 支持缩放
        if (Build.VERSION.SDK_INT >= 11) {
            webSettings.setPluginState(WebSettings.PluginState.ON);
            webSettings.setDisplayZoomControls(false);// 支持缩放
        }
        webSettings.setSupportZoom(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 扩大比例的缩放
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        // 自适应屏幕
        if (Build.VERSION.SDK_INT > 14) {
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        }
        webSettings.setBlockNetworkImage(false);// 不能屏蔽图片，验证码是图片
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        // 设置web chrome client用于更新progress
        webview.setWebChromeClient(new MyWebChromeClient());
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                if (request.getUrl() != null && request.getUrl().toString().startsWith("tel:")) {
                    final String number = ConfigManager.getInstance().getServiceTel();
                    Dialog dialog = UIUtils.createTwoButtonDialog(getContext(), getString(R.string.house_entrust),
                            getString(R.string.call_to_entrust) + number, getString(android.R.string.cancel),
                            getString(R.string.call_now), null, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent);
                                }
                            });
                    showAlert(dialog);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
    }

}
